package com.hk.commons.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hk.commons.serializer.JacksonObjMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
public class JacksonUtil {

    private JacksonUtil(){};

    public static final ObjectMapper objectMapper = new JacksonObjMapper();

    /**
     * Json字符串转Map对象
     *
     */
    public static <K,V> Map<K,V> toMap(String jsonStr) {
        return toObject(jsonStr,new TypeReference<Map<K,V>>(){});
    }

    /**
     * Json字符串转List对象
     *
     */
    public static <E> List<E> toList(String jsonStr) {
        return toObject(jsonStr,new TypeReference<List<E>>(){});
    }

    /**
     * Json字符串转Java对象
     */
    public static <T> T toJavaBean(String jsonStr, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonStr, clazz);
        } catch (JsonProcessingException e) {
            log.error("json 转换异常：[{}]",e.getMessage());
        }
        return null;
    }

    /**
     * Json字符串转Java对象
     */
    public static <T> T toJavaBean(byte[] bstr, Class<T> clazz) {
        try {
            return objectMapper.readValue(bstr, clazz);
        } catch (IOException e) {
            log.error("json 转换异常：[{}]",e.getMessage());
        }
        return null;
    }

    /**
     * Json字符串转对象、集合等
     */
    public static <T> T toObject(String jsonStr, TypeReference<T> type) {
        try {
            return objectMapper.readValue(jsonStr, type);
        } catch (JsonProcessingException e) {
            log.error("json 转换异常：[{}]",e.getMessage());
        }
        return null;
    }

    /**
     * Json字符串转对象、集合等
     */
    public static <T> T toObject(byte[] bstr, TypeReference<T> type) {
        try {
            return objectMapper.readValue(bstr, type);
        } catch (IOException e) {
            log.error("json 转换异常：[{}]",e.getMessage());
        }
        return null;
    }

    /**
     * 对象、集合等转json字符串
     */
    public static <T> String toJsonStr(T entity) {
        try {
            return objectMapper.writeValueAsString(entity);
        } catch (JsonProcessingException e) {
            log.error("json 转换异常：[{}]",e.getMessage());
        }
        return null;
    }

    /**
     * 对象、集合等转json字符串
     */
    public static <T> byte[] toJsonBytes(T entity) {
        try {
            return objectMapper.writeValueAsBytes(entity);
        } catch (JsonProcessingException e) {
            log.error("json 转换异常：[{}]",e.getMessage());
        }
        return null;
    }

}
